<template>
  <div class="dericelnfo">
    <el-header>
      <el-select v-if="activeName === 'first'" v-model="querryInfo.smartstatus" clearable @clear="getEquipment()"
        placeholder="智能设备状态" style="width: 200px;">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-select v-else v-model="querryInfo.familystatus" clearable @clear="getEquipment()" placeholder="家居设备状态"
        style="width: 200px;">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker v-model="equitmentForm.dateArr" type="datetimerange" :picker-options="pickerOptions"
        range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right">
      </el-date-picker>
      <el-input v-model="querryInfo.homenum" placeholder="房号" clearable @clear="getEquipment()"
        style="width: 200px;"></el-input>
      <el-button type="primary" @click="getEquipment()" icon="el-icon-search">查询</el-button>
    </el-header>
    <el-main>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="用户管理" name="first">
          <el-table ref='multipleTable' :model="equitmentForm" :data="equitmentList" tooltip-effect="dark"
            style="width: 100%">
            <el-table-column label="单元名称" align="center">
              <template slot-scope="scope">{{ scope.row.unitname }}</template>
            </el-table-column>
            <el-table-column label="幢号" align="center">
              <template slot-scope="scope">{{ scope.row.buildnum }}</template>
            </el-table-column>
            <el-table-column label="房号" align="center">
              <template slot-scope="scope">{{ scope.row.homenum }}</template>
            </el-table-column>
            <el-table-column label="房主" align="center">
              <template slot-scope="scope">{{ scope.row.homename }}</template>
            </el-table-column>
            <el-table-column label="空调" align="center">
              <template slot-scope="scope">{{ scope.row.airnum }}</template>
            </el-table-column>
            <el-table-column label="Wi-Fi" align="center">
              <template slot-scope="scope">{{ scope.row.wifiname }}</template>
            </el-table-column>
            <el-table-column label="洗衣机" align="center">
              <template slot-scope="scope">{{ scope.row.washnum }}</template>
            </el-table-column>
            <el-table-column label="授予时间" align="center">
              <template slot-scope="scope">{{ formatDateTime(scope.row.createtime) }}</template>
            </el-table-column>
            <el-table-column label="状态" align="center">
              <template slot-scope="scope">
                {{ getStatusLabel(scope.row.smartstatus) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.smartstatus" :active-value="1" :inactive-value="2"
                  @change="handleChangeStatus(scope.row)"></el-switch>
              </template>
            </el-table-column>
          </el-table>
          <pagination style="text-align: right;" :page="querryInfo.currPage" :componentTotal="unitTotal"
            @changeRows="setRows" @changePage="setPage">
          </pagination>
        </el-tab-pane>
        <el-tab-pane label="配置管理" name="second">
          <el-table ref='multipleTable' :model="equitmentForm" :data="familyList" tooltip-effect="dark"
            style="width: 100%">
            <el-table-column label="单元名称" align="center">
              <template slot-scope="scope">{{ scope.row.unitname }}</template>
            </el-table-column>
            <el-table-column label="幢号" align="center">
              <template slot-scope="scope">{{ scope.row.buildnum }}</template>
            </el-table-column>
            <el-table-column label="房号" align="center">
              <template slot-scope="scope">{{ scope.row.homenum }}</template>
            </el-table-column>
            <el-table-column label="房主" align="center">
              <template slot-scope="scope">{{ scope.row.homename }}</template>
            </el-table-column>
            <el-table-column label="书桌" align="center">
              <template slot-scope="scope">{{ scope.row.homedesk }}</template>
            </el-table-column>
            <el-table-column label="椅子" align="center">
              <template slot-scope="scope">{{ scope.row.homechair }}</template>
            </el-table-column>
            <el-table-column label="衣柜" align="center">
              <template slot-scope="scope">{{ scope.row.homeclothes }}</template>
            </el-table-column>
            <el-table-column label="授予时间" align="center">
              <template slot-scope="scope">{{ formatDateTime(scope.row.createtime) }}</template>
            </el-table-column>
            <el-table-column label="状态" align="center">
              <template slot-scope="scope">
                {{ gethomeStatusLabel(scope.row.familystatus) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.familystatus" :active-value="1" :inactive-value="2"
                  :active-color="scope.row.familystatus === 1 ? '#13ce66' : '#ff4949'"
                  :inactive-color="scope.row.familystatus === 2 ? '#ff4949' : '#ff4949'"
                  @change="handleChangeStatus(scope.row)"></el-switch>
              </template>
            </el-table-column>
          </el-table>
          <pagination style="text-align: right;" :page="querryInfo.currPage" :componentTotal="unitTotal"
            @changeRows="setRows" @changePage="setPage">
          </pagination>
        </el-tab-pane>
      </el-tabs>
    </el-main>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
export default {
  data() {
    return {
      querryInfo: {
        smartstatus: '',
        familystatus: '',
        homenum: '',
        startDate: '',
        endDate: '',
        currPage: 0,
        pageNum: 10,
        token: sessionStorage.token
      },
      equitmentForm: {
        id: '',
        smartstatus: '',
        familystatus: '',
        dateArr: [],
      },
      equitmentList: [],
      familyList: [],
      activeName: 'first', // 默认选中的 Tab
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
      value2: '',
      statusOptions: [
        { value: '1', label: '完好' },
        { value: '2', label: '待维修' },
      ]
    };
  },
  computed: {
    getStatusLabel() {
      return (smartstatus) => {
        const status = this.statusOptions.find(option => option.value == smartstatus);
        return status ? status.label : '待维修';
      };
    },
    gethomeStatusLabel() {
      return (familystatus) => {
        const status = this.statusOptions.find(option => option.value == familystatus);
        return status ? status.label : '待维修';
      };
    }
  },
  watch: {
    "equitmentForm.dateArr"(val) {
      if (val && val.length === 2) {
        this.querryInfo.startDate = this.formatDateTime(val[0]);
        this.querryInfo.endDate = this.formatDateTime(val[1]);
      } else {
        this.querryInfo.startDate = '';
        this.querryInfo.endDate = '';
      }
    },
  },
  mounted() {
    this.getEquipment();
  },
  components: {
    Pagination
  },
  methods: {
    setRows(val) {
      this.querryInfo.pageNum = val;
      this.getEquipment();
    },
    setPage(val) {
      this.querryInfo.currPage = val - 1;
      this.getEquipment();
    },
    async handleChangeStatus(row) {
      // 先询问用户是否确认修改
      if (this.activeName === 'first') {
        this.$confirm('确认修改状态？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 用户确认修改
          this.equitmentForm.id = row.id;
          this.equitmentForm.smartstatus = row.smartstatus;
          const { data: res } = await this.axios.post('/house/updatesmartStatus', this.equitmentForm);
          console.log(res);
          this.$message.success('修改成功');
          this.getEquipment();
        }).catch(() => {
          // 用户取消修改
          this.$message.info('已取消修改');
          // 恢复原始状态
          row.smartstatus = row.smartstatus === 1 ? 2 : 1;
        });
      } else {
        this.$confirm('确认修改状态？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 用户确认修改
          this.equitmentForm.id = row.id;
          this.equitmentForm.familystatus = row.familystatus;
          const { data: res } = await this.axios.post('/house/updatefamilyStatus', this.equitmentForm);
          console.log(res);
          this.$message.success('修改成功');
          this.getEquipment();
        }).catch(() => {
          // 用户取消修改
          this.$message.info('已取消修改');
          // 恢复原始状态
          row.familystatus = row.familystatus === 1 ? 2 : 1;
        });
      }

    },
    formatDateTime(createtime) {
      if (!createtime) return '';
      const date = new Date(createtime);
      const year = date.getFullYear().toString().slice(-2); // 获取年份的后两位
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份并补零
      const day = String(date.getDate()).padStart(2, '0'); // 获取日期并补零
      const hours = String(date.getHours()).padStart(2, '0'); // 获取小时并补零
      const minutes = String(date.getMinutes()).padStart(2, '0'); // 获取分钟并补零
      const seconds = String(date.getSeconds()).padStart(2, '0'); // 获取秒并补零
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    async getEquipment() {
      if (this.activeName == 'first') {
        const { data: res } = await this.axios.get("/house/searchdeviceList", {
          params: this.querryInfo,
          headers: {
            token: sessionStorage.token
          }
        });
        console.log(res);
        this.equitmentList = res.data;
        this.unitTotal = res.total;
        console.log(this.equitmentList);
      } else {
        const { data: res } = await this.axios.get("/house/searchdeviceList", {
          params: this.querryInfo,
          headers: {
            token: sessionStorage.token
          }
        });
        console.log(res);
        this.familyList = res.data;
        this.unitTotal = res.total;
        console.log(this.familyList);
      }
    },
    add() {
      // 录入方法
      console.log('录入');
    },
    reset() {
      // 重置方法
      console.log('重置');
    },
    handleTabClick(tab) {
      // 处理 Tab 切换事件
      console.log('切换到:', tab.name);
      this.getEquipment();
    }
  }
}
</script>

<style scoped lang="scss">
.dericelnfo {
  margin: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  height: 100%;

  .el-header {
    min-width: 1250px;
    background-color: #fff;
    margin: 10px;
    line-height: 40px;

    .el-input,
    .el-select {
      margin: 5px 20px;
    }
  }

  .el-main {
    .el-tabs {
      margin: 20px;

      .el-tabs__header {
        margin-bottom: 20px;

        .el-tabs__nav-wrap::after {
          display: none;
          /* 去掉底部的下划线 */
        }

        .el-tabs__active-bar {
          display: none;
          /* 去掉选中的下划线 */
        }

        .el-tabs__item {
          &.is-active {
            color: #409EFF;
            /* 选中 Tab 的文字颜色 */
            font-weight: bold;
            /* 选中 Tab 的文字加粗 */
          }
        }
      }

      .el-tabs__content {
        padding: 20px;
        background-color: #f5f7fa;
        border: 1px solid #dcdfe6;
        border-top: none;
      }
    }
  }
}
</style>
